﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Controls;
using Caliburn.Micro;
using OI.Async;
using OI.DataModel;
using OI.Events;
using OI.Framework;

namespace OI.ViewModels
{
    [Export(typeof(SourceViewModel))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class SourceViewModel : Screen
    {
        public string Header { get { return "source"; } }
        public BindableCollection<OISource> Items { get; set; }
        public IEventAggregator Events { get; set; }
        public bool ItemsAreNew { get; set; }

        [ImportingConstructor]
        public SourceViewModel(IEventAggregator events)
		{
            Events = events;
		}


        // when this view loads, async populate categories
        protected override void OnViewLoaded(object view)
        {
            if (Items == null)
            {
                 Coroutine.BeginExecute(LoadSources());
            }
        }


        public IEnumerator<IResult> LoadSources()
        {
            Events.Publish(new ShowBusy { Caption = "loading sources..." });

            var sq = new CatalogQuery<OISource>(Configuration.Jurisdiction.ID);
            yield return sq;

            // filter by "source filter"
            var dstResults = (from s in sq.Results select s).Distinct(new OISourceEqualityCompare());

            Items = new BindableCollection<OISource>(dstResults);
            Items.Insert(0, new OISource { Name = "All", Filter = "All" });

            ItemsAreNew = true;
            NotifyOfPropertyChange(() => Items);
            ItemsAreNew = false;

            Events.Publish(new HideBusy());
        }


        // make sure 'all' item initially checked
        public void ItemLoaded(OISource item, RadioButton source)
        {
            if (ItemsAreNew)
            {
                source.IsChecked = (item.ID == 0);
            }
        }


        // called when an item is selected
        public void Select(OISource item)
        {
            Events.Publish(new ChangeCatalogFilter()
            {
                FilterType = ChangeCatalogFilter.Filter.Source,
                FilterItem = item
            });
        }
    }
}
